package com.example.myapplication

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import androidx.core.widget.doBeforeTextChanged
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.Fragment
import com.example.myapplication.databinding.FragmentFirstBinding
import okhttp3.internal.trimSubstring
import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.web3j.crypto.Credentials
import org.web3j.crypto.Sign
import org.web3j.crypto.Wallet
import org.web3j.crypto.WalletUtils
import org.web3j.ens.contracts.generated.PublicResolver.deploy
import org.web3j.protocol.Web3j
import org.web3j.protocol.core.DefaultBlockParameter
import org.web3j.protocol.core.methods.response.EthGetBalance
import org.web3j.protocol.core.methods.response.TransactionReceipt
import org.web3j.protocol.http.HttpService
import org.web3j.tx.Contract
import org.web3j.tx.ManagedTransaction
import org.web3j.tx.Transfer
import org.web3j.utils.Convert
import org.web3j.utils.Numeric
import java.io.File
import java.math.BigDecimal
import java.security.Security
import java.util.*
import java.util.regex.Pattern
import kotlin.concurrent.thread


/**
 * A simple [Fragment] subclass as the default destination in the navigation.
 */
class FirstFragment : Fragment() {

    private var _binding: FragmentFirstBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!
    private var web3jServer: Web3j? = null
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {

        _binding = FragmentFirstBinding.inflate(inflater, container, false)

        // Android registers its own BC provider. As it might be outdated and might not include
        // all needed ciphers, we substitute it with a known BC bundled in the app.
        // Android's BC has its package rewritten to "com.android.org.bouncycastle" and because
        // of that it's possible to have another BC implementation loaded in VM.
        // Android registers its own BC provider. As it might be outdated and might not include
        // all needed ciphers, we substitute it with a known BC bundled in the app.
        // Android's BC has its package rewritten to "com.android.org.bouncycastle" and because
        // of that it's possible to have another BC implementation loaded in VM.
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME)
        Security.insertProviderAt(BouncyCastleProvider(), 1)
        return binding.root

    }

    private fun visibleLayout(id: Int) {
        binding.layoutCreateWalletByDefault.visibility = if (id == 1) View.VISIBLE else View.GONE
        binding.layoutCreateWalletByKeystore.visibility = if (id == 2) View.VISIBLE else View.GONE
        binding.layoutCreateWalletBySecurity.visibility = if (id == 3) View.VISIBLE else View.GONE
        binding.layoutCreateWalletByMen.visibility = if (id == 4) View.VISIBLE else View.GONE
        binding.layoutTransform.visibility = if (id == 5) View.VISIBLE else View.GONE
        binding.tvWalletInfo.text = ""
    }


//    override fun onClick(v:View?) {
//        when (v.id) {
//            R.id.xxx -> {
//
//            }
//            else -> {}
//        }
//    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.btnCreateWalletDefault.setOnClickListener { visibleLayout(1) }
        binding.btnCreateWalletFromKeystore.setOnClickListener { visibleLayout(2) }
        binding.btnCreateWalletFromSecurity.setOnClickListener { visibleLayout(3) }
        binding.btnCreateWalletFromMne.setOnClickListener { visibleLayout(4) }
        binding.btnTransform.setOnClickListener { visibleLayout(5) }


        var imageView: XXXView

        val list = listOf<String>("1", "1", "1", "1", "1")
        list.forEachIndexed { index, item ->

            context?.let { _context ->
                imageView = XXXView(_context)
                val parameter = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
                imageView.layoutParams = parameter
//                imageView.id= R.ids.xxxx
//                imageView.setOnClickListener(this)
                binding.llcGroup.addView(imageView)
            }
        }

        binding.btnCreate.setOnClickListener {
//            Web3Util.instance.createWallet(
//                requireContext(),
//                "asdoiadifbv",
//                "124124"
//            )

//            Web3Util.instance.init(requireContext(), "")
////            Web3Util.instance.loadC(requireContext(), "xxxxx")
////            Web3Util.instance.createWallet("", "", true)
//            Web3Util.instance.undoResetStore("")

//            Web3Util.instance.hasWallet(requireContext(), "")
//            Web3Util.instance.restoreWalletByMnemonic(requireContext(), "", "olive school outer cancel organ hair fee crouch dizzy shoe toward such", "")
//            Web3Util.instance.changeWalletPassword(
//                "",
//                "olive school outer cancel organ hair fee crouch dizzy shoe toward such"
//            )

//            println(
//                "resule =  ${
//                    Web3Util.instance.unlockWallet(
//                        "olive schol outer cancel organ hair fee crouch dizzy shoe toward such"
//                    )
//                }"
//            )

            val walletFile = Web3Util.instance.createBip44Wallet("12412", requireContext().cacheDir)


            println("创建钱包=====================================")
//            val wallet = Bip44WalletUtils.generateBip44Wallet("1234", requireContext().cacheDir)
            val loadCredentials = WalletUtils.loadCredentials(
                "12412",
                requireContext().cacheDir.absolutePath + File.separator + walletFile.filename
            )
            println("地址11： ${loadCredentials.address}")
            println("公钥： ${loadCredentials.ecKeyPair.publicKey.toString(16)}")
            println("私钥： ${loadCredentials.ecKeyPair.privateKey.toString(16)}")
            println("助记词：${walletFile.mnemonic}")
            println("钱包文件名${walletFile.filename}")
            println("创建钱包=====================================")
        }

        binding.btnWalletCreateByDefault.setOnClickListener {
            val wallet = WalletUtils.generateBip39Wallet(
                binding.tvDefault.text.toString(), requireContext().cacheDir
            )
            val loadCredentials = WalletUtils.loadCredentials(
                binding.tvDefault.text.toString(),
                requireContext().cacheDir.absolutePath + File.separator + wallet.filename
            )
            binding.tvWalletDescription.text = "地址： ${loadCredentials.address}\n公钥： ${
                loadCredentials.ecKeyPair.publicKey.toString(16)
            }\n私钥： ${loadCredentials.ecKeyPair.privateKey.toString(16)}\n助记词：${wallet.mnemonic}\n钱包文件名: ${wallet.filename}"
            println("地址： ${loadCredentials.address}")
            println("公钥： ${loadCredentials.ecKeyPair.publicKey.toString(16)}")
            println("私钥： ${loadCredentials.ecKeyPair.privateKey.toString(16)}")
            println("助记词：${wallet.mnemonic}")
            println("钱包文件名${wallet.filename}")
        }

        // 通过助记词恢复钱包
        binding.btnWalletCreateByMne.setOnClickListener {
            val wallet = WalletUtils.generateBip39WalletFromMnemonic(
                binding.etPwd.text.toString(),
                binding.etMne.text.toString(),
                requireContext().cacheDir
            )
            val loadCredentials = WalletUtils.loadCredentials(
                binding.etPwd.text.toString(),
                requireContext().cacheDir.absolutePath + File.separator + wallet.filename
            )
            binding.tvWalletDescription.text = "地址： ${loadCredentials.address}\n公钥： ${
                loadCredentials.ecKeyPair.publicKey.toString(16)
            }\n私钥： ${loadCredentials.ecKeyPair.privateKey.toString(16)}\n助记词：${wallet.mnemonic}\n钱包文件名: ${wallet.filename}"

            println("地址： ${loadCredentials.address}")
            println("公钥： ${loadCredentials.ecKeyPair.publicKey.toString(16)}")
            println("私钥： ${loadCredentials.ecKeyPair.privateKey.toString(16)}")
            println("助记词：${wallet.mnemonic}")
            println("钱包文件名${wallet.filename}")
        }

        // 密钥生成钱包
        binding.btnCreateWalletBySecurity.setOnClickListener {
            val loadCredentials = Credentials.create(binding.etSecurity.text.toString())

            val wallet = Wallet.createLight("123123123", loadCredentials.ecKeyPair)
            WalletUtils.generateWalletFile(
                "123123123", loadCredentials.ecKeyPair, context?.cacheDir, false
            )
            binding.tvWalletDescription.text = "地址： ${loadCredentials.address}\n公钥： ${
                loadCredentials.ecKeyPair.publicKey.toString(16)
            }\n私钥： ${loadCredentials.ecKeyPair.privateKey.toString(16)}\n"
            println("地址： ${loadCredentials.address}")
            println("公钥： ${loadCredentials.ecKeyPair.publicKey.toString(16)}")
            println("私钥： ${loadCredentials.ecKeyPair.privateKey.toString(16)}")

            // 私钥不可以反推出助记词， 下面的代码是生成了一个新的
//            var privArray = loadCredentials.ecKeyPair.privateKey.toByteArray()
//            if (privArray.size == 33 && privArray[0] == 0.toByte()) {
//                val tmpArray = ByteArray(privArray.size - 1)
//                System.arraycopy(privArray, 1, tmpArray, 0, tmpArray.size)
//                privArray = tmpArray
//            }
//            println("助记词：${MnemonicUtils.generateMnemonic(privArray)}")
//            println("钱包文件名${wallet.filename}")
        }


        /**
         * 通过 keystore 加载钱包
         */
        binding.btnCreateWalletByKeystore.setOnClickListener {
            val loadCredentials = WalletUtils.loadCredentials(
                "123123123",
                requireContext().cacheDir.absolutePath + File.separator + binding.etKeystore.text.toString()
            )

            binding.tvWalletDescription.text = "地址： ${loadCredentials.address}\n公钥： ${
                loadCredentials.ecKeyPair.publicKey.toString(16)
            }\n私钥： ${loadCredentials.ecKeyPair.privateKey.toString(16)}\n"

            println("地址： ${loadCredentials.address}")
            println("公钥： ${loadCredentials.ecKeyPair.publicKey.toString(16)}")
            println("私钥： ${loadCredentials.ecKeyPair.privateKey.toString(16)}")
        }
//        connectETHClient()


        binding.btnQueryBalance.setOnClickListener {
            getBalanceOf()
        }

        binding.btnTransformTo.setOnClickListener {
            transformTo()
        }


        // TODO 六哥看这里
        binding.btnSign.setOnClickListener {

//            val mnemonic =
//                "fitness garden skin ladder soap submit awful luggage hundred avocado donor alpha"
////            val mnemonic = "tornado retire time muffin fault device edit helmet tray family rally soda"
////            val ecKeyPair = Bip44WalletUtils.loadBip44Credentials("1234", mnemonic)
////            val fileName = Bip44WalletUtils.generateWalletFile("1234", ecKeyPair.ecKeyPair, requireContext().cacheDir, false)
//
//
//            val pwd = "1231222223123"
//
//
//            val walletFile = Web3Util.instance.generateBip44WalletFileByMnemonic(
//                pwd,
//                mnemonic,
//                requireContext().cacheDir
//            )
//            val loadCredentials = WalletUtils.loadCredentials(
//                pwd,
//                requireContext().cacheDir.absolutePath + File.separator + walletFile.filename
//            )
//            println("助记词导入========================================================")
//            println("公钥: ${loadCredentials.ecKeyPair.publicKey.toString(16)}")
//            println("私钥: ${loadCredentials.ecKeyPair.privateKey.toString(16)}")
//            println("地址: ${loadCredentials.address}")
//            println("助记词：${walletFile.mnemonic}")
//            println("助记词导入========================================================")
            // 这个是王凡的
//            val json = JSONObject(
//                "{\n" + "            \"domain\":\n" + "            {\n" + "                \"chainId\": 223344,\n" + "                \"name\": \"Decentralization Identity Factory\",\n" + "                \"verifyingContract\": \"0x83fDD81A60fD37DAF816de088Ba8365D6637cd82\",\n" + "                \"version\": \"v1.0.0\"\n" + "            },\n" + "            \"message\":\n" + "            {\n" + "                \"callSalt\": 1,\n" + "                \"deploySalt\": \"0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6\",\n" + "                \"didOwner\": \"0xe72098bc2b890d0a4203d2e3ccf1e5eb86ba68a4\",\n" + "                \"factoryData\": \"0xbc36789e7a1e281436464229828f817d6612f7b477d66591ff96a9e064bcc98a\",\n" + "                \"initData\":\n" + "                {\n" + "                    \"alternateOwners\":\n" + "                    [\n" + "                        {\n" + "                            \"alternateOwner\": \"0x953f49522b63c2b0110928b31835dbbac12e194e\",\n" + "                            \"timeLock\": 14400\n" + "                        }\n" + "                    ]\n" + "                },\n" + "                \"version\": 1\n" + "            },\n" + "            \"primaryType\": \"CreateDIDParam\",\n" + "            \"types\":\n" + "            {\n" + "                \"AlternateOwner\":\n" + "                [\n" + "                    {\n" + "                        \"name\": \"alternateOwner\",\n" + "                        \"type\": \"address\"\n" + "                    },\n" + "                    {\n" + "                        \"name\": \"timeLock\",\n" + "                        \"type\": \"uint256\"\n" + "                    }\n" + "                ],\n" + "                \"CreateDIDParam\":\n" + "                [\n" + "                    {\n" + "                        \"name\": \"version\",\n" + "                        \"type\": \"uint256\"\n" + "                    },\n" + "                    {\n" + "                        \"name\": \"didOwner\",\n" + "                        \"type\": \"address\"\n" + "                    },\n" + "                    {\n" + "                        \"name\": \"callSalt\",\n" + "                        \"type\": \"uint256\"\n" + "                    },\n" + "                    {\n" + "                        \"name\": \"deploySalt\",\n" + "                        \"type\": \"bytes32\"\n" + "                    },\n" + "                    {\n" + "                        \"name\": \"factoryData\",\n" + "                        \"type\": \"bytes\"\n" + "                    },\n" + "                    {\n" + "                        \"name\": \"initData\",\n" + "                        \"type\": \"InitData\"\n" + "                    }\n" + "                ],\n" + "                \"EIP712Domain\":\n" + "                [\n" + "                    {\n" + "                        \"name\": \"name\",\n" + "                        \"type\": \"string\"\n" + "                    },\n" + "                    {\n" + "                        \"name\": \"version\",\n" + "                        \"type\": \"string\"\n" + "                    },\n" + "                    {\n" + "                        \"name\": \"chainId\",\n" + "                        \"type\": \"uint256\"\n" + "                    },\n" + "                    {\n" + "                        \"name\": \"verifyingContract\",\n" + "                        \"type\": \"address\"\n" + "                    }\n" + "                ],\n" + "                \"InitData\":\n" + "                [\n" + "                    {\n" + "                        \"name\": \"alternateOwners\",\n" + "                        \"type\": \"AlternateOwner[]\"\n" + "                    }\n" + "                ]\n" + "            }\n" + "        }"
//            )

            //这个是姜振的
//            val json = JSONObject(
//                "{\"domain\":{\"chainId\":4,\"name\":\"Ether Mail\",\"verifyingContract\":\"0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC\",\"version\":\"1\"},\"message\":{\"contents\":\"Hello, Bob!\",\"from\":{\"name\":\"Cow\",\"wallets\":[\"0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826\",\"0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF\"]},\"to\":[{\"name\":\"Bob\",\"wallets\":[\"0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB\",\"0xB0BdaBea57B0BDABeA57b0bdABEA57b0BDabEa57\",\"0xB0B0b0b0b0b0B000000000000000000000000000\"]}]},\"primaryType\":\"Mail\",\"types\":{\"EIP712Domain\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"version\",\"type\":\"string\"},{\"name\":\"chainId\",\"type\":\"uint256\"},{\"name\":\"verifyingContract\",\"type\":\"address\"}],\"Group\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"members\",\"type\":\"Person[]\"}],\"Mail\":[{\"name\":\"from\",\"type\":\"Person\"},{\"name\":\"to\",\"type\":\"Person[]\"},{\"name\":\"contents\",\"type\":\"string\"}],\"Person\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"wallets\",\"type\":\"address[]\"}]}}"
//            )
//?
//            val param = "@sdf,fo34f20f23@xxxxxxxxxxxxxxxxxxxx"
//            val urlIdentify = param.substring(0, param.lastIndexOf("@") + 1)
//            println(urlIdentify)
//            val json = "0xa8364ddec6483751481244956086a7756733f921"
////            val hashData = StructuredDataEncoder(json.toString()).hashStructuredData()

//            val eck =
//                ECKeyPair.create(Numeric.toBigInt("0x127a1e57ca11e258260a0d5ee205309aa72fa3be745febd71db34d43ba51793e"))
//            val cre =
//                Credentials.create("0x127a1e57ca11e258260a0d5ee205309aa72fa3be745febd71db34d43ba51793e")
////                Credentials.create("0xcd3b766ccdd6ae721141f452c550ca635964ce71")
////
//
//            val eip712 = StructuredDataEncoder(param)
//
//            val byteArray = Sign.getEthereumMessageHash(eip712.hashStructuredData())
//            val signData = Sign.signPrefixedMessage(eip712.hashStructuredData(), cre.ecKeyPair)
//            println("signed1 : ${byte2HexString(signData)}")
//            val signData0 =
////                Sign.signMessage(json.toByteArray(), cre.ecKeyPair)
//                Sign.signMessage(param.toString().toByteArray(Charsets.UTF_8), eck)
////【】】【【【【
//            val a = Sign.signMessage(Numeric.hexStringToByteArray(json), eck, false)
//            val signData1 =
//                Sign.signMessage(json.toString().toByteArray(), eck)
//            val signData2 =
//                Sign.signPrefixedMessage(json.toString().toByteArray(Charsets.UTF_8), eck)
////
//            val signData3 = Sign.signMessage(hashData, cre.ecKeyPair)
//            val signData4 = Sign.signMessage(hashData, cre.ecKeyPair, false)
//            val signData5 = Sign.signPrefixedMessage(hashData, cre.ecKeyPair)
//
//
//            println("privateKey : ${cre.ecKeyPair.privateKey.toString(16)}")
//            println("publicKey : ${cre.address}")
//            println("signed : ${byte2HexString(a)}")
//            println("signed0 : ${byte2HexString(signData0)}")
//            println("signed1 : ${byte2HexString(signData1)}")
//            println("signed2 : ${byte2HexString(signData2)}")
//            println("signed3 : ${byte2HexString(signData3)}")
//            println("signed4 : ${byte2HexString(signData4)}")
//            println("signed5 : ${byte2HexString(signData5)}")


//            val pri = "0x127a1e57ca11e258260a0d5ee205309aa72fa3be745febd71db34d43ba51793e"
            val pri = "0xf13458f5b2c686afc4739a47a322f5fe79577a6a0996d1029037039e8d79e2ec"
//            val arr = transformInfoEip712
//            val arr = createDIDEip712
//            val arr = addContact
//            val arr = deleteContact
            val arr = undoReset
//
//            val signData = NewEip712StructDataEncoder(arr).hashStructuredData()

//
            val cred = Credentials.create(pri)
//            val address = cred.address
//            val s = Sign.signMessage(arr.toByteArray(), cred.ecKeyPair)
//            val r = byte2HexString(s)
//
////            var arrbytes = Numeric.hexStringToByteArray(signData)
////            var arrbytes1 = arr.toByteArray()
//
//            val rs = Sign.getEthereumMessageHash(signData)
//            val rss = Numeric.toHexString(rs)
//
//
//            val sssss = Sign.signMessage(signData, cred.ecKeyPair, false)
//
//            val sr = byte2HexString(sssss)

            val data = NewEip712StructDataEncoder(arr)
            println(data.jsonMessageObject.toString())
            val signData =data.hashStructuredData()
            val sr =  byte2HexString(
                Sign.signMessage(
                    signData,
                    cred.ecKeyPair,
                    false
                )
            )
            println("Na_Sign=======> $sr")
//
//            val cred = Credentials.create(pri)
//            val address = cred.address
//            val s = Sign.signMessage(arr.toByteArray(), cred.ecKeyPair)
//            val r = byte2HexString(s)
//
//            var arrbytes = Numeric.hexStringToByteArray(arr)
//            var arrbytes1 = arr.toByteArray()
//
//            val rs = Sign.getEthereumMessageHash(arrbytes)
//
//            val rss = Numeric.toHexString(rs)
//
//            val sssss = Sign.signMessage(rs, cred.ecKeyPair, false)
//
//            val sr = byte2HexString(sssss)

//            println("=======> $sr")

            //获取webview
            val webView = WebView(this.requireContext())
            //设置为ChromeClinet 才能执行js代码
            //设置为ChromeClinet 才能执行js代码
            binding.root.addView(webView)
            //加载本地html
            webView.loadUrl("file:///android_asset/web3js/SignStructuredData.html")
            val webChromeClient = WebChromeClient()
            webView.webChromeClient = webChromeClient
            webView.webViewClient = MyWebViewClient(
                arr,
//                eck.privateKey.toString(16)
                pri
            ) {
                println("Js_sign===> " + it)
            }
            //设置开启js支持
            //设置开启js支持
            webView.getSettings().setJavaScriptEnabled(true)
            // 是否支持缩放
            // 是否支持缩放
            webView.settings.setSupportZoom(true)
            //加载本地html

        }


        binding.etText.doBeforeTextChanged { text, start, count, after ->
            pre = text.toString()

        }
        binding.etText.doOnTextChanged { text, start, before, count ->

            if (text?.startsWith(" ") == true) {
                binding.etText.setText(text.trim())
            } else {

                text?.let {
                    Log.d("Quinn", "FirstFragment ===> onViewCreated() called $pre")
                    if (StringTokenizer(it.toString()).countTokens() > 12) {
                        binding.etText.setText(pre)
                        binding.etText.setSelection(start)
                        return@doOnTextChanged
                    }

                    val matcher = arrayTypePattern.matcher(it)
                    if (matcher.find()) {
                        val sub = it.replace(arrayTypeRegex, " ").replace(Regex("[^a-z, ]"), "")
                        binding.etText.setText(sub)
                        sub
                    } else {
                        it
                    }
                }?.let {
                    val length = StringTokenizer(it.toString()).countTokens()
                    binding.tvWalletDescription.text = String.format("%s/12", length)
                }
            }
        }

//        binding.etText.doAfterTextChanged {
//            val length = it.toString().split(" ").size
//            val size = if (it?.endsWith(" ") == true) length - 1 else length
//            val matcher = arrayTypePattern1.matcher(it.toString())
//            matcher.find()
//            Log.d("Quinn", "FirstFragment ===> onViewCreated() called${ matcher.groupCount()}")
//
//            binding.tvWalletDescription.text = String.format("%s/12", size)
//        }

    }

    var pre = ""

    val arrayTypeRegex = Regex("[ ]{2,}")
    val arrayTypePattern = Pattern.compile("[ ]{2,}")
    val arrayTypePattern1 = Pattern.compile("[ ]+")

    inner class MyWebViewClient(
        private val json: String,
        private val privateKey: String,
        private val callback: SuccessCallback<String>
    ) : WebViewClient() {
        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            url.takeIf { url.contains("?signature=") }?.let {
                callback.invoke(it.trimSubstring(it.indexOf("?signature=") + "?signature=".length))
            } ?: kotlin.run {
                view.loadUrl(
                    "javascript:signMessageByEIP712('$json', '${
//                    "javascript:signMessage('$json', '${
                        privateKey
                    }');"
                )
            }
        }
    }

    val undoReset = """
        {
				"types": {
					"EIP712Domain": [{
						"name": "name",
						"type": "string"
					}, {
						"name": "version",
						"type": "string"
					}, {
						"name": "chainId",
						"type": "uint256"
					}, {
						"name": "verifyingContract",
						"type": "address"
					}],
					"RawTx": [{
						"name": "to",
						"type": "address"
					}, {
						"name": "value",
						"type": "uint256"
					}, {
						"name": "data",
						"type": "bytes"
					}],
					"TransactionInfo": [{
						"name": "txs",
						"type": "RawTx[]"
					}, {
						"name": "nonce",
						"type": "uint256"
					}, {
						"name": "refundToken",
						"type": "address"
					}, {
						"name": "refundReceiver",
						"type": "address"
					}, {
						"name": "refundGasPrice",
						"type": "uint256"
					}, {
						"name": "refundBaseGasLimit",
						"type": "uint256"
					}, {
						"name": "otherPayer",
						"type": "address"
					}]
				},
				"primaryType": "TransactionInfo",
				"domain": {
					"name": "Decentralization Identity",
					"version": "1",
					"chainId": "256",
					"verifyingContract": "0x2b11CA59E305CC8752F418900a9111FFA6225d73"
				},
				"message": {
					"nonce": "1",
					"otherPayer": "0x0000000000000000000000000000000000000000",
					"refundBaseGasLimit": "0x0",
					"refundGasPrice": "0x0",
					"refundReceiver": "0x0000000000000000000000000000000000000000",
					"refundToken": "0x0000000000000000000000000000000000000000",
					"txs": [{
						"data": "0x",
						"to": "0x2b11CA59E305CC8752F418900a9111FFA6225d73",
						"value": "0x0"
					}]
				}
			}
    """.trimIndent()

    val createDIDEip712 = """
        {
            "domain":
            {
                "name": "Decentralization Identity Factory",
                "version": "v1.0.0",
                "chainId": "256",
                "verifyingContract": "0x2dCA55f435ecb3b1eAfAa2765e04aDaf6B4A70de"
            },
            "message":
            {
                "version": 1,
                "didOwner": "0x6cd1588eAbB939500138178a5fd31e64eB74De23",
                "callSalt": 1,
                "deploySalt": "0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6",
                "factoryData": "0xbc36789e7a1e281436464229828f817d6612f7b477d66591ff96a9e064bcc98a",
                "initData":
                {
                    "alternateOwners":
                    [
                        {
                            "alternateOwner": "0x6bf5371ae9c3ccf46a61359746be26d61c01bf4f",
                            "timeLock": 3600
                        }
                    ]
                }
            },
            "primaryType": "CreateDIDParam",
            "types":
            {
                "EIP712Domain":
                [
                    {
                        "name": "name",
                        "type": "string"
                    },
                    {
                        "name": "version",
                        "type": "string"
                    },
                    {
                        "name": "chainId",
                        "type": "uint256"
                    },
                    {
                        "name": "verifyingContract",
                        "type": "address"
                    }
                ],
                "CreateDIDParam":
                [
                    {
                        "name": "version",
                        "type": "uint256"
                    },
                    {
                        "name": "didOwner",
                        "type": "address"
                    },
                    {
                        "name": "callSalt",
                        "type": "uint256"
                    },
                    {
                        "name": "deploySalt",
                        "type": "bytes32"
                    },
                    {
                        "name": "factoryData",
                        "type": "bytes"
                    },
                    {
                        "name": "initData",
                        "type": "InitData"
                    }
                ],
                "InitData":
                [
                    {
                        "name": "alternateOwners",
                        "type": "AlternateOwner[]"
                    }
                ],
                "AlternateOwner":
                [
                    {
                        "name": "alternateOwner",
                        "type": "address"
                    },
                    {
                        "name": "timeLock",
                        "type": "uint256"
                    }
                ]
            }
        }
    """.trimIndent()

    val addContact = """
        {
            "domain":
            {
                "name": "Decentralization Identity",
                "version": "1",
                "chainId": "256",
                "verifyingContract": "0xe5a0882CB9897841AC377865A4a7a90262025218"
            },
            "message":
            {
                "txs":
                [
                    {
                        "to": "0xe5a0882CB9897841AC377865A4a7a90262025218",
                        "value": 0,
                        "data": "0x8ca049000000000000000000000000006ffcbb92adb560f9e0f509d2a7a06362b9a08e6a0000000000000000000000000000000000000000000000000000000000000e10"
                    }
                ],
                "nonce": "0",
                "refundToken": "0x0000000000000000000000000000000000000000",
                "refundReceiver": "0x0000000000000000000000000000000000000000",
                "refundGasPrice": 0,
                "refundBaseGasLimit": 0,
                "otherPayer": "0x0000000000000000000000000000000000000000"
            },
            "primaryType": "TransactionInfo",
            "types":
            {
                "EIP712Domain":
                [
                    {
                        "name": "name",
                        "type": "string"
                    },
                    {
                        "name": "version",
                        "type": "string"
                    },
                    {
                        "name": "chainId",
                        "type": "uint256"
                    },
                    {
                        "name": "verifyingContract",
                        "type": "address"
                    }
                ],
                "TransactionInfo":
                [
                    {
                        "name": "txs",
                        "type": "RawTx[]"
                    },
                    {
                        "name": "nonce",
                        "type": "uint256"
                    },
                    {
                        "name": "refundToken",
                        "type": "address"
                    },
                    {
                        "name": "refundReceiver",
                        "type": "address"
                    },
                    {
                        "name": "refundGasPrice",
                        "type": "uint256"
                    },
                    {
                        "name": "refundBaseGasLimit",
                        "type": "uint256"
                    },
                    {
                        "name": "otherPayer",
                        "type": "address"
                    }
                ],
                "RawTx":
                [
                    {
                        "name": "to",
                        "type": "address"
                    },
                    {
                        "name": "value",
                        "type": "uint256"
                    },
                    {
                        "name": "data",
                        "type": "bytes"
                    }
                ]
            }
        }
    """.trimIndent()


    val deleteContact = """
        {
            "domain":
            {
                "name": "Decentralization Identity",
                "version": "1",
                "chainId": "256",
                "verifyingContract": "0xe5a0882CB9897841AC377865A4a7a90262025218"
            },
            "message":
            {
                "txs":
                [
                    {
                        "to": "0xe5a0882CB9897841AC377865A4a7a90262025218",
                        "value": 0,
                        "data": "0x8ca049000000000000000000000000006ffcbb92adb560f9e0f509d2a7a06362b9a08e6a0000000000000000000000000000000000000000000000000000000000000000"
                    }
                ],
                "nonce": "0",
                "refundToken": "0x0000000000000000000000000000000000000000",
                "refundReceiver": "0x0000000000000000000000000000000000000000",
                "refundGasPrice": 0,
                "refundBaseGasLimit": 0,
                "otherPayer": "0x0000000000000000000000000000000000000000"
            },
            "primaryType": "TransactionInfo",
            "types":
            {
                "EIP712Domain":
                [
                    {
                        "name": "name",
                        "type": "string"
                    },
                    {
                        "name": "version",
                        "type": "string"
                    },
                    {
                        "name": "chainId",
                        "type": "uint256"
                    },
                    {
                        "name": "verifyingContract",
                        "type": "address"
                    }
                ],
                "TransactionInfo":
                [
                    {
                        "name": "txs",
                        "type": "RawTx[]"
                    },
                    {
                        "name": "nonce",
                        "type": "uint256"
                    },
                    {
                        "name": "refundToken",
                        "type": "address"
                    },
                    {
                        "name": "refundReceiver",
                        "type": "address"
                    },
                    {
                        "name": "refundGasPrice",
                        "type": "uint256"
                    },
                    {
                        "name": "refundBaseGasLimit",
                        "type": "uint256"
                    },
                    {
                        "name": "otherPayer",
                        "type": "address"
                    }
                ],
                "RawTx":
                [
                    {
                        "name": "to",
                        "type": "address"
                    },
                    {
                        "name": "value",
                        "type": "uint256"
                    },
                    {
                        "name": "data",
                        "type": "bytes"
                    }
                ]
            }
        }
    """.trimIndent()

    val transformInfoEip712 = """
{
			"domain": {
				"chainId": "256",
				"name": "Decentralization Identity",
				"verifyingContract": "0x10BD5679E83a15137DFDd4E5f7216bfd6B026b31",
				"version": "1"
			},
			"message": {
				"nonce": "2",
				"otherPayer": "0x0000000000000000000000000000000000000000",
				"refundBaseGasLimit": "0x0",
				"refundGasPrice": "0x0",
				"refundReceiver": "0x0000000000000000000000000000000000000000",
				"refundToken": "0x0000000000000000000000000000000000000000",
				"txs": [{
					"data": "0x",
					"to": "0x10BD5679E83a15137DFDd4E5f7216bfd6B026b31",
					"value": "0x0"
				}]
			},
			"primaryType": "TransactionInfo",
			"types": {
				"EIP712Domain": [{
					"name": "name",
					"type": "string"
				}, {
					"name": "version",
					"type": "string"
				}, {
					"name": "chainId",
					"type": "uint256"
				}, {
					"name": "verifyingContract",
					"type": "address"
				}],
				"RawTx": [{
					"name": "to",
					"type": "address"
				}, {
					"name": "value",
					"type": "uint256"
				}, {
					"name": "data",
					"type": "bytes"
				}],
				"TransactionInfo": [{
					"name": "txs",
					"type": "RawTx[]"
				}, {
					"name": "nonce",
					"type": "uint256"
				}, {
					"name": "refundToken",
					"type": "address"
				}, {
					"name": "refundReceiver",
					"type": "address"
				}, {
					"name": "refundGasPrice",
					"type": "uint256"
				}, {
					"name": "refundBaseGasLimit",
					"type": "uint256"
				}, {
					"name": "otherPayer",
					"type": "address"
				}]
			}
		}
    """.trimIndent()

    private fun byte2HexString(signData5: Sign.SignatureData): String? {

        val retval5 = ByteArray(65)
//        System.arraycopy(signData5.r, 0, retval5, 0, 32)
//        System.arraycopy(signData5.s, 0, retval5, 32, 32)
//        System.arraycopy(signData5.v, 0, retval5, 64, 1)


        System.arraycopy(signData5.r, 0, retval5, 0, 32)
        System.arraycopy(signData5.s, 0, retval5, 32, 32)
        System.arraycopy(signData5.v, 0, retval5, 64, 1)

        return Numeric.toHexString(retval5)
    }

    /**
     * 转账
     */
    private fun transformTo() {
        if (web3jServer == null) return
//        if (credentials == null) return;
        //开始发送0.01 =eth到指定地址
        thread {
            val address_to = "0x0B253D3392C9442c5634b9dC3bF35909449dfADB"

            val loadCredentials =
                Credentials.create("8b6b702d548f6442704f28fe08734a3f5a1b571d865330859af98e3f1752348e")
//            val loadCredentials = WalletUtils.loadCredentials(
//                "123123123",
//                requireContext().cacheDir.absolutePath + File.separator + "UTC--2022-07-06T11-11-20.522000000Z--ef228c4fddfb9102b8046de39e8640b26f84af9b.json"
//            )
            try {
                // 发起转账
                val send: TransactionReceipt = Transfer.sendFunds(
                    web3jServer,
                    loadCredentials,
                    address_to,
                    BigDecimal("1000000000001.90"),
                    Convert.Unit.FINNEY
                ).send()

                requireActivity().runOnUiThread {
                    binding.tvWalletInfo.text =
                        "Transaction complete: \ntrans hash=${send.transactionHash} \nfrom :${send.from} \nto:${send.to} \n gas used=${send.gasUsed}\n status: ${send.status}"
                }

//                // 发布合约
                val send1 = deploy(
                    web3jServer,
                    loadCredentials,
                    ManagedTransaction.GAS_PRICE,
                    Contract.GAS_LIMIT,
                    "0x9195f4E6c9227210AE946a23A393d90ea0044003"
                ).send()
                println("智能合约地址： ${send1.contractAddress}")
//                PublicResolver.load(
//                    send1.contractAddress, web3jServer, loadCredentials,
//                    ManagedTransaction.GAS_PRICE,
//                    Contract.GAS_LIMIT
//                ).transactionReceipt.ifPresent {  }

            } catch (e: Exception) {
                e.printStackTrace()

            }
        }

    }

    private fun connectETHClient() {
        thread {
            // 链接本地客户端
            web3jServer = Web3j.build(HttpService("HTTP://10.60.100.45:7545"))
//        val web3jServer = Web3j.build(HttpService("HTTP://127.0.0.1:7545"))
            println("============>$web3jServer")
            val web3jServerVersion = web3jServer?.web3ClientVersion()?.send()?.web3ClientVersion
            println("web3jServerVersion ++=======>   $web3jServerVersion")
        }

    }

    private fun getBalanceOf() {
        if (web3jServer == null) return
        thread {
            val address = "0x48fDe94e882d04D0d9DAb80198CdFC0B5c41cE9e"//等待查询余额的地址
            //第二个参数：区块的参数，建议选最新区块
            val balance: EthGetBalance =
                web3jServer?.ethGetBalance(address, DefaultBlockParameter.valueOf("latest"))
                    ?.send()!!
            //格式转化 wei-ether
            val blanceETH =
                Convert.fromWei(balance.balance.toString(), Convert.Unit.ETHER).toPlainString()
//                    .concat("ether");
            requireActivity().runOnUiThread {
                binding.tvWalletInfo.text = "余额： $blanceETH"
            }
        }

//
    }

    // poverty pepper reform equip place craft bread victory potato soul exotic jaguar
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}typealias SuccessCallback<T> = (callback: T) -> Unit


class XXXView(context: Context) : View(context) {

    val field: Any? = null

    init {

        View.inflate(context, R.layout.fragment_second, null)
    }


    fun setText(text: String) {
        invalidate()
    }
}